package com.ayf.payment.game.api.service.platform.impl;

import cn.hutool.core.collection.CollUtil;
import com.ayf.payment.game.api.config.SystemInitialization;
import com.ayf.payment.game.api.dto.MerchantAccountOptions;
import com.ayf.payment.game.api.dto.MerchantConfigDTO;
import com.ayf.payment.game.api.dto.criteria.OrderInfoCriteria;
import com.ayf.payment.game.api.dto.platform.MerchantSettleDTO;
import com.ayf.payment.game.api.dto.platform.SettleConfigDTO;
import com.ayf.payment.game.api.entity.MerchantBalanceRecord;
import com.ayf.payment.game.api.entity.platform.MerchantCashOut;
import com.ayf.payment.game.api.entity.platform.MerchantSettle;
import com.ayf.payment.game.api.mapper.MerchantBalanceRecordMapper;
import com.ayf.payment.game.api.mapper.platform.MerchantCashOutMapper;
import com.ayf.payment.game.api.mapper.platform.MerchantSettleMapper;
import com.ayf.payment.game.api.service.MerchantAccountService;
import com.ayf.payment.game.api.service.MerchantPayOrderService;
import com.ayf.payment.game.api.service.MerchantRepository;
import com.ayf.payment.game.api.service.MerchantService;
import com.ayf.payment.game.api.service.platform.MerchantCashOutService;
import com.ayf.payment.game.api.service.platform.MerchantSettleService;
import com.ayf.payment.game.api.service.platform.SettleConfigService;
import com.ayf.payment.game.api.type.YesAndNo;
import com.ayf.payment.game.api.utils.DateUtils;
import com.ayf.payment.game.api.utils.RandomStrUtils;
import com.ayf.payment.game.api.utils.SnowFlakeUtils;
import com.swwx.charm.commons.lang.utils.BeanConvertUtils;
import com.swwx.charm.commons.lang.utils.LogPortal;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class MerchantSettleServiceImpl implements MerchantSettleService {

    @Resource
    private MerchantSettleMapper merchantSettleMapper;
    @Resource
    private MerchantAccountService merchantAccountService;

    @Resource
    private MerchantRepository merchantRepository;
    @Resource
    private SystemInitialization systemInitialization;
    @Resource
    private MerchantBalanceRecordMapper merchantBalanceRecordMapper;

    @Autowired
    private SettleConfigService settleConfigService;
    @Autowired
    private MerchantService merchantService;
    @Autowired
    private MerchantCashOutService merchantCashOutService;
    @Autowired
    private MerchantPayOrderService merchantPayOrderService;
    @Autowired
    private MerchantCashOutMapper merchantCashOutMapper;


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void inserts(List<MerchantSettleDTO> MerchantSettles, Map<Integer, MerchantSettleDTO> porxyMap) {
        String settleDate= DateUtils.dateToString(DateUtils.getNowDate(), DateUtils.formatPattern_Short);
        //普通商户结算
        MerchantSettles.forEach((merchantSettleDTO)->{
            String settleOrdeCreateStr = DateUtils.dateToString(DateUtils.getNowDate(), DateUtils.formatPattern_full_01);
            String settleOrderNo = "S" + settleOrdeCreateStr + RandomStrUtils.createRandom(true,8);
            MerchantSettle merchantSettle= BeanConvertUtils.convert(merchantSettleDTO, MerchantSettle.class);
            merchantSettle.setSettleOrderNo(settleOrderNo);
            merchantSettle.setSettleDate(Integer.parseInt(settleDate));
            merchantSettle.setCreateTime(new Date());
            BigDecimal merchantIncome=merchantSettle.getMerchantSettleAmount();
            if(!porxyMap.isEmpty()){
                if(null != porxyMap.get(merchantSettle.getMerchantId()) ) {

                    merchantIncome=merchantIncome.add(porxyMap.get(merchantSettle.getMerchantId()).getMerchantSettleAmount());
                    porxyMap.remove(merchantSettle.getMerchantId());
                }
            }
            merchantSettle.setMerchantSettleAmount(merchantIncome);
            MerchantConfigDTO merchantConfigDTO=merchantRepository.get(merchantSettleDTO.getMerchantId());
            if(YesAndNo.NO.equals(merchantConfigDTO.getSettleCycleCustom())){
                merchantConfigDTO.setSettleCycle(systemInitialization.settleConfigDTO().getSettleCycle());
            }
            if(merchantConfigDTO.getSettleCycle()==0) {
                MerchantAccountOptions merchantAccountOptions = new MerchantAccountOptions();
                merchantAccountOptions.setFreezing(BigDecimal.ZERO);
                merchantAccountOptions.setMerchantId(merchantSettle.getMerchantId());
                merchantAccountOptions.setOptionCash(merchantIncome.negate());
                merchantAccountOptions.setCashWithdrawal(merchantIncome);
                merchantAccountOptions.setOptionType("生成结算单");
                merchantAccountService.updateMerchantAccount(merchantAccountOptions);
                merchantSettle.setSettleStatus(1);
                merchantSettle.setMerchantSettleType(0);
            }else{
                MerchantAccountOptions merchantAccountOptions = new MerchantAccountOptions();
                merchantAccountOptions.setFreezing(merchantIncome);
                merchantAccountOptions.setMerchantId(merchantSettle.getMerchantId());
                merchantAccountOptions.setOptionCash(merchantIncome.negate());
                merchantAccountOptions.setCashWithdrawal(BigDecimal.ZERO);
                merchantAccountOptions.setCashWithdrawalIng(BigDecimal.ZERO);
                merchantAccountOptions.setOptionType("生成结算单");
                merchantAccountService.updateMerchantAccount(merchantAccountOptions);
                merchantSettle.setSettleStatus(0);
                merchantSettle.setMerchantSettleType(1);
            }
            merchantSettleMapper.insert(merchantSettle);
        });
        //代理商结算
        porxyMap.forEach((k,merchantSettleDTO1)->{
            if(null!=k && null!=merchantSettleDTO1 && null!=merchantSettleDTO1.getMerchantSettleAmount() && merchantSettleDTO1.getMerchantSettleAmount().compareTo(BigDecimal.ZERO)==1) {
                String settleOrdeCreateStr = DateUtils.dateToString(DateUtils.getNowDate(), DateUtils.formatPattern_full_01);
                String settleOrderNo = "S" + settleOrdeCreateStr + RandomStrUtils.createRandom(true, 8);
                MerchantSettle merchantSettle = BeanConvertUtils.convert(merchantSettleDTO1, MerchantSettle.class);
                merchantSettle.setSettleOrderNo(settleOrderNo);
                merchantSettle.setSettleDate(Integer.parseInt(settleDate));
                merchantSettle.setCreateTime(new Date());

                MerchantConfigDTO merchantConfigDTO = merchantRepository.get(merchantSettleDTO1.getMerchantId());
                if (YesAndNo.NO.equals(merchantConfigDTO.getSettleCycleCustom())) {
                    merchantConfigDTO.setSettleCycle(systemInitialization.settleConfigDTO().getSettleCycle());
                }
                if (merchantConfigDTO.getSettleCycle() == 0) {
                    MerchantAccountOptions merchantAccountOptions = new MerchantAccountOptions();
                    merchantAccountOptions.setFreezing(BigDecimal.ZERO);
                    merchantAccountOptions.setMerchantId(merchantSettle.getMerchantId());
                    merchantAccountOptions.setOptionCash(merchantSettleDTO1.getMerchantSettleAmount().negate());
                    merchantAccountOptions.setCashWithdrawal(merchantSettleDTO1.getMerchantSettleAmount());
                    merchantAccountOptions.setOptionType("生成结算单");
                    merchantAccountService.updateMerchantAccount(merchantAccountOptions);
                    merchantSettle.setSettleStatus(1);
                    merchantSettle.setMerchantSettleType(0);
                } else {
                    MerchantAccountOptions merchantAccountOptions = new MerchantAccountOptions();
                    merchantAccountOptions.setFreezing(merchantSettleDTO1.getMerchantSettleAmount());
                    merchantAccountOptions.setMerchantId(merchantSettle.getMerchantId());
                    merchantAccountOptions.setOptionCash(merchantSettleDTO1.getMerchantSettleAmount().negate());
                    merchantAccountOptions.setCashWithdrawal(BigDecimal.ZERO);
                    merchantAccountOptions.setCashWithdrawalIng(BigDecimal.ZERO);
                    merchantAccountOptions.setOptionType("生成结算单");
                    merchantAccountService.updateMerchantAccount(merchantAccountOptions);
                    merchantSettle.setSettleStatus(0);
                    merchantSettle.setMerchantSettleType(1);
                }
                merchantSettleMapper.insert(merchantSettle);
            }
        });
    }

    @Override
    public void updateMerchantSettleStatuByTradeNumber(String tradeNumber,int settleStatus) {
        Example example = new Example(MerchantSettle.class);
        example.createCriteria().andEqualTo("settleOrderNo",tradeNumber);
        MerchantSettle merchantSettle=new MerchantSettle();
        merchantSettle.setSettleStatus(settleStatus);
        merchantSettleMapper.updateByExampleSelective(merchantSettle,example);
    }

    @Override
    public Map<Integer, Map<String, Object>> selectSumSettle(OrderInfoCriteria cri) {
        return merchantSettleMapper.selectSumSettle(cri);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void daySettle(MerchantSettleDTO dto, Map<Integer, Map<String, Object>> withdrawalMap, Map<Integer, Map<String, Object>> payMap) {
        SettleConfigDTO settleConfigDTO = settleConfigService.getSettleConfig();
        BigDecimal minWithdrawalAmt = BigDecimal.ZERO;
        if (settleConfigDTO !=null){
            minWithdrawalAmt = settleConfigDTO.getMinWithdrawalAmount();
            if (minWithdrawalAmt==null){
                minWithdrawalAmt = BigDecimal.ZERO;
            }
        }
        BigDecimal splitAmt =dto.getSplitAmt()==null?BigDecimal.ZERO:dto.getSplitAmt();
        if (dto.getMerchantSettleAmount().compareTo(minWithdrawalAmt) > 0) {
            MerchantSettle merchantSettle = BeanConvertUtils.convert(dto, MerchantSettle.class);
            merchantSettle.setCreateTime(new Date());

            MerchantConfigDTO merchantConfigDTO=merchantRepository.get(merchantSettle.getMerchantId());
            if(YesAndNo.NO.equals(merchantConfigDTO.getSettleCycleCustom())){
                merchantConfigDTO.setSettleCycle(systemInitialization.settleConfigDTO().getSettleCycle());
            }
            if(merchantConfigDTO.getSettleCycle()==0) { //D+0
                MerchantAccountOptions merchantAccountOptions = new MerchantAccountOptions();
                merchantAccountOptions.setMerchantId(merchantSettle.getMerchantId());
                merchantAccountOptions.setOptionCash(dto.getMerchantSettleAmount().negate());
                merchantAccountOptions.setCashWithdrawal(dto.getMerchantSettleAmount().subtract(splitAmt));
                merchantAccountOptions.setOptionType("D+0生成结算单");
                if (splitAmt.compareTo(BigDecimal.ZERO)>0){
                    merchantAccountOptions.setSplitAmt(splitAmt.negate());
                }
                merchantAccountService.updateMerchantAccount(merchantAccountOptions);
                merchantSettle.setSettleStatus(1);
                merchantSettle.setMerchantSettleType(0);
                merchantSettleMapper.insert(merchantSettle);
            }else{
                MerchantAccountOptions merchantAccountOptions = new MerchantAccountOptions();
                merchantAccountOptions.setMerchantId(merchantSettle.getMerchantId());
                merchantAccountOptions.setOptionCash(dto.getMerchantSettleAmount().negate());
                if (splitAmt.compareTo(BigDecimal.ZERO)>0){
                    if (dto.getMerchantSettleAmount().compareTo(splitAmt)==0){
                        merchantSettle.setSettleStatus(1); // 全部分账结算
                    } else {
                        merchantSettle.setSettleStatus(2); // 部分分账自动结算
                    }
                    merchantSettle.setSettledAmt(splitAmt);
                    merchantAccountOptions.setSplitAmt(splitAmt.negate());
                    merchantAccountOptions.setFreezing(dto.getMerchantSettleAmount().subtract(splitAmt));
                } else {
                    merchantSettle.setSettleStatus(0);
                    merchantAccountOptions.setFreezing(dto.getMerchantSettleAmount());
                }
                merchantAccountOptions.setOptionType("D+1生成结算单");
                merchantAccountService.updateMerchantAccount(merchantAccountOptions);

                merchantSettle.setMerchantSettleType(1);
                merchantSettleMapper.insert(merchantSettle);
            }
            if (splitAmt.compareTo(BigDecimal.ZERO)>0){
                // 新增分账自动结算记录
                Date currentDate = DateUtils.getNowDate();
                MerchantCashOut merchantCashOut = new MerchantCashOut();
                merchantCashOut.setBatchTime(currentDate);
                merchantCashOut.setCreateTime(currentDate);
                merchantCashOut.setMerchantId(merchantSettle.getMerchantId());
                merchantCashOut.setFee(BigDecimal.ZERO);
                merchantCashOut.setAmount(splitAmt);
                merchantCashOut.setActualAmount(splitAmt);
                merchantCashOut.setOperatorTime(currentDate);
                merchantCashOut.setSettleDate(merchantSettle.getSettleDate());
                merchantCashOut.setSettleOrderOn(merchantSettle.getSettleOrderNo());
                merchantCashOut.setTradeStatus(Short.valueOf("3"));
                merchantCashOut.setFinishTime(currentDate);
                merchantCashOut.setIsAtuoSettle(0);
                merchantCashOut.setTradeNumber("SP".concat(SnowFlakeUtils.getUniqueId()));
                merchantCashOut.setCashOutType(1);
                merchantCashOut.setBankName("金额自动打款到支付产品开户银行卡");
                merchantCashOutMapper.insertSelective(merchantCashOut);
            }
        }else {
            if (splitAmt.compareTo(BigDecimal.ZERO)>0){
                // 新增分账自动结算记录
                Date currentDate = DateUtils.getNowDate();
                MerchantCashOut merchantCashOut = new MerchantCashOut();
                merchantCashOut.setBatchTime(currentDate);
                merchantCashOut.setCreateTime(currentDate);
                merchantCashOut.setMerchantId(dto.getMerchantId());
                merchantCashOut.setFee(BigDecimal.ZERO);
                merchantCashOut.setAmount(splitAmt);
                merchantCashOut.setActualAmount(splitAmt);
                merchantCashOut.setOperatorTime(currentDate);
                merchantCashOut.setSettleDate(dto.getSettleDate());
                merchantCashOut.setSettleOrderOn(dto.getSettleOrderNo());
                merchantCashOut.setTradeStatus(Short.valueOf("3"));
                merchantCashOut.setFinishTime(currentDate);
                merchantCashOut.setIsAtuoSettle(0);
                merchantCashOut.setTradeNumber("SP".concat(SnowFlakeUtils.getUniqueId()));
                merchantCashOut.setCashOutType(1);
                merchantCashOut.setBankName("金额自动打款到支付产品开户银行卡");
                merchantCashOutMapper.insertSelective(merchantCashOut);
                MerchantAccountOptions merchantAccountOptions = new MerchantAccountOptions();
                merchantAccountOptions.setMerchantId(dto.getMerchantId());
                merchantAccountOptions.setOptionCash(splitAmt.negate());
                merchantAccountOptions.setSplitAmt(splitAmt.negate());
                merchantAccountOptions.setOptionType("D+1金额自动打款到支付产品开户银行卡");
                merchantAccountService.updateMerchantAccount(merchantAccountOptions);
            }
        }
        BigDecimal withdrawalAmount = splitAmt;
        if (withdrawalMap.get(dto.getMerchantId()) != null) {
            withdrawalAmount = withdrawalAmount.add((BigDecimal) withdrawalMap.get(dto.getMerchantId()).get("merchantTotalWithdrawal"));
        }
        if (payMap.get(dto.getMerchantId()) != null) {
            withdrawalAmount = withdrawalAmount.add((BigDecimal) payMap.get(dto.getMerchantId()).get("merchantTotalPay"));
        }
        if (withdrawalAmount.compareTo(BigDecimal.ZERO) > 0 || dto.getMerchantSettleAmount().compareTo(BigDecimal.ZERO) > 0 || dto.getYesterdaySettleAmount() != null) {
            MerchantBalanceRecord merchantBalanceRecord = new MerchantBalanceRecord();
            merchantBalanceRecord.setWithdrawalAmount(withdrawalAmount);
            merchantBalanceRecord.setMerchantId(dto.getMerchantId());
            merchantBalanceRecord.setSettleDate(DateUtils.dateToString(new Date(), DateUtils.formatPattern));
            if (dto.getYesterdaySettleAmount() == null) {
                merchantBalanceRecord.setSettleAmount(BigDecimal.ZERO);
            } else {
                merchantBalanceRecord.setSettleAmount(dto.getYesterdaySettleAmount());
            }
            merchantBalanceRecord.setCashWithdrawal(dto.getMerchantSettleAmount());
            merchantBalanceRecordMapper.insertSelective(merchantBalanceRecord);
        }
    }

    @Override
    public int updateSettleAmtAndSettleStatusBySettleOrderNo(String settleOrderNo, BigDecimal settleAmt, Integer settleStatus) {
        return merchantSettleMapper.updateSettleAmtAndSettleStatusBySettleOrderNo(settleOrderNo,settleAmt,settleStatus);
    }

    @Override
    public MerchantSettleDTO getMerchantSettleBySettleOrderNo(String settleOrderOn) {
        MerchantSettle merchantSettle = new MerchantSettle();
        merchantSettle.setSettleOrderNo(settleOrderOn);
        return BeanConvertUtils.convert(merchantSettleMapper.selectOne(merchantSettle),MerchantSettleDTO.class);
    }

    @Override
    public void merchantSettleCreate(String needSettleDate) {
        String traceId = SnowFlakeUtils.getTraceId();
        Date currentDate = DateUtils.stringToDate(needSettleDate);
        Integer date = DateUtils.dateToInteger(currentDate);
        Integer settleDate = DateUtils.dateToInteger(DateUtils.getDayBeforeDay(currentDate,-1));
        List<MerchantSettleDTO> settleList = merchantService.getSettleList(date, null);
        if (CollUtil.isEmpty(settleList)) {
            LogPortal.info("{} 手动执行结算单日期:{} 没有记录",traceId,settleDate);
            return;
        }
        OrderInfoCriteria orderCriteria = new OrderInfoCriteria();
        String yesterday = DateUtils.dateToString(currentDate,DateUtils.formatPattern);
        orderCriteria.setStartTime(yesterday + " 00:00:00");
        orderCriteria.setEndTime(yesterday + " 23:59:59");
        orderCriteria.setDate(date);
        //提现
        Map<Integer, Map<String, Object>> withdrawalMap = merchantCashOutService.selectSumWithdrawal(orderCriteria);
        //代付
        Map<Integer, Map<String, Object>> payMap = merchantPayOrderService.selectSumPay(orderCriteria);

        String settleOrdeCreateStr = "S" + DateUtils.dateToString(currentDate, "yyMMdd");
        for (MerchantSettleDTO dto :settleList){
            try {
                String settleOrderNo = settleOrdeCreateStr + SnowFlakeUtils.getUniqueId();
                dto.setSettleDate(settleDate);
                dto.setSettleOrderNo(settleOrderNo);
                daySettle(dto, withdrawalMap, payMap);
            } catch (Exception e) {
                LogPortal.error("{} 商户ID[{}]结算失败,发生了[{}]异常，错误描述[{}]，本次处理的商户信息为[{}]",e,traceId, dto.getMerchantId(), e.getClass().getName(), e.getMessage(), dto);
            }
        }
        LogPortal.info("{} 手动执行结算单[{}]执行完成，本次处理的商户总数量为[{}]",traceId,settleDate,settleList.size());
    }
}
